const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'
const bCrypt = require('bcryptjs')
//修改密码
router.post('/updatePassword', async (req, res) => {
    //先判断新旧密码是否符合要求
    if (req.body.origin_password.length < 6 || req.body.origin_password.length > 20
    || req.body.new_password.length < 6 || req.body.new_password.length > 20) {
        res.json({
            'code': 403,
            'result': 'false',
            'type': 'password_length_error',
            'content': '密码格式错误'
        })
    }
    else {
        //验证token与原密码
        const result = jwt.verify(req.body.token, SECRET)
        let sql = 'select * from user where username = ?'
        db.base(sql, result.username, response => {
            if ( response.length > 0 && bCrypt.compareSync(req.body.origin_password,response[0].password)){
                const salt = bCrypt.genSaltSync(10)
                let data = bCrypt.hashSync(req.body.new_password,salt)
                let sql = 'update user set password = ?'
                db.base(sql, data, () => {
                    res.json({
                        'code': 200,
                        'result': 'true',
                        'type': 'success_modify',
                        'content': '修改成功'
                    })
                })

            }
            else {
                res.json({
                    'code': 403,
                    'result': 'false',
                    'type': 'request_error',
                    'content': 'token错误或原密码不匹配'
                })
            }
        })
    }
})

module.exports = router
